package com.hehanpeng.springbootapi.dto;

import com.hehanpeng.springbootapi.domain.Book;
import com.hehanpeng.springbootapi.util.Convert;
import com.hehanpeng.springbootapi.util.CustomBeanUtils;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.BeanUtils;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

/**
 * @author hehanpeng
 * @date 2018/4/24 19:48
 */
public class BookDto {
    @NotBlank
    private String author;
    @Length(max = 20)
    private String description;
    @NotBlank
    private String name;
    @NotNull
    private int status;

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public void convert(Book book) {
        new BookConvert().convert(this, book);
    }

    public Book convert() {
        return new BookConvert().convert(this);
    }

    private class BookConvert implements Convert<BookDto, Book> {

        @Override
        public Book convert(BookDto bookDto, Book book) {
            String[] nullPropertyNames = CustomBeanUtils.getNullPropertyNames(bookDto);
            BeanUtils.copyProperties(bookDto, book, nullPropertyNames);
            return book;
        }

        @Override
        public Book convert(BookDto bookDto) {
            Book book = new Book();
            BeanUtils.copyProperties(bookDto, book);
            return book;
        }
    }
}
